package com.gri.saas;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.gri.utils.GriUtils;

/**
 * Servlet implementation class Registration
 */
public class Registration extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Registration() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processData(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processData(request,response);
	}

	private void processData(HttpServletRequest request,
			HttpServletResponse response) {
		String name = request.getParameter("nm");
		String email = request.getParameter("email");
		String userName = request.getParameter("un");
		String company = request.getParameter("cmpny");
		String password = request.getParameter("pwd");
		String confirmPwd = request.getParameter("cpwd");
		request.getSession().setAttribute("regMessage", "");
		
		if(null == name || name.isEmpty() || null == email || email.isEmpty() || null == userName || userName.isEmpty()|| null == password || password.isEmpty() || null== confirmPwd || confirmPwd.isEmpty()){
			String regMessage = "Please fill the mandatory fields";
			setMessageAndForwardToRegistrationPage(request,response,regMessage);
		}else if(!password.equals(confirmPwd)){
			String regMessage = "Password does not match with the confirm password";
			setMessageAndForwardToRegistrationPage(request,response,regMessage);
		} else if(!validEmailFormat(email)){
			String regMessage = "Email is not in valid format";
			setMessageAndForwardToRegistrationPage(request,response,regMessage);
		} else {
			Connection con = null;
			PreparedStatement stmt = null;
			try{
				con = GriUtils.getConnection();			
				if(!validateEmailExists(con,email)){
					Integer roleId = getRoleId(con);
					stmt = con.prepareStatement("Insert into tbl_customer(cust_name,email,username,company,password,role_id,status)" +
							"values (?,?,?,?,?,?,?)");
					stmt.setString(1, name);
					stmt.setString(2, email);
					stmt.setString(3, userName);
					stmt.setString(4, company!=null ? company:"");
					stmt.setString(5, password);
					stmt.setInt(6, roleId);
					stmt.setString(7,"Active");
					Integer retVal = stmt.executeUpdate();
					stmt.close();
					if(retVal !=1){
						String regMessage = "User could not be created because of some technical issue. Please try again";
						setMessageAndForwardToRegistrationPage(request,response,regMessage);
					} else {
						String regMessage = "Registration completed successfully.";
						setMessageAndForwardToRegistrationPage(request,response,regMessage);
					}
					
				} else{
					String regMessage = "Email already exists. Please enter some different email";
					setMessageAndForwardToRegistrationPage(request,response,regMessage);
				}
				con.close();
			}catch(Exception ex){
				
			}finally{
				try{			
					if(con != null){
						con.close();
					}
				}catch(Exception ex){
					
				}
			}
		}
		
	}

	private Boolean validateEmailExists(Connection con, String email) throws Exception{
		Statement stmt = con.createStatement();
		ResultSet rs = stmt.executeQuery("Select * from tbl_customer where lower(email) = '" + email.toLowerCase() + "'");
		while(null != rs && rs.next()){
			rs.close();
			stmt.close();
			return Boolean.TRUE;
		}
		return Boolean.FALSE;
	}
	

	private Integer getRoleId(Connection con) throws Exception{
		Statement stmt = con.createStatement();
		ResultSet rs = stmt.executeQuery("Select role_id from tbl_roles where lower(role_name) = 'user'");
		Integer roleId = null;
		while(rs.next()){
			roleId = rs.getInt(1);
			break;
		}
		return roleId;
	}
	
	private void setMessageAndForwardToRegistrationPage(HttpServletRequest request,  HttpServletResponse response, String message){
		request.getSession().setAttribute("regMessage", message);
		GriUtils.forwardToPage(request, response, "registration.jsp");
	}

	private Boolean validEmailFormat( String emailAddress){
		Pattern pattern = Pattern.compile("^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$",
				Pattern.CASE_INSENSITIVE);
		Matcher matcher = pattern.matcher(emailAddress);
		if(!matcher.matches()){
			return Boolean.FALSE;
		}
		return Boolean.TRUE;
	}

}
